/**
 * 优化的工单Store
 * 包含：乐观更新、防重复提交、加载状态管理
 */
import { defineStore } from 'pinia'
import { TicketService } from '../services/tickets'
import { ElMessage } from 'element-plus'

export const useTicketsStore = defineStore('tickets', {
  state: () => ({
    tickets: [],
    loading: false,
    error: null,
    
    // 提交状态管理
    submitting: false,
    lastSubmitTime: 0,
    submitDebounceTime: 2000, // 2秒防抖
    
    // 乐观更新相关
    optimisticTickets: [], // 乐观添加的工单（pending状态）
    pendingOperations: new Map(), // 正在进行的操作
    
    filters: {
      status: '',
      priority: '',
      category: '',
      assignee: '',
      keyword: '',
      dateRange: []
    },
    pagination: {
      page: 1,
      size: 20,
      total: 0
    },
    selectedTickets: [],
    bulkActions: {
      visible: false,
      action: '',
      loading: false
    }
  }),

  getters: {
    // 合并实际工单和乐观工单
    allTickets: (state) => {
      return [...state.optimisticTickets, ...state.tickets]
    },
    
    // 筛选后的工单（包含乐观更新）
    filteredTickets: (state) => {
      const allTickets = [...state.optimisticTickets, ...state.tickets]
      let filtered = allTickets

      // 状态筛选
      if (state.filters.status) {
        filtered = filtered.filter(ticket => ticket.status === state.filters.status)
      }

      // 优先级筛选
      if (state.filters.priority) {
        filtered = filtered.filter(ticket => ticket.priority === state.filters.priority)
      }

      // 分类筛选
      if (state.filters.category) {
        filtered = filtered.filter(ticket => ticket.category === state.filters.category)
      }

      // 负责人筛选
      if (state.filters.assignee) {
        filtered = filtered.filter(ticket => ticket.assigneeId === state.filters.assignee)
      }

      // 关键词搜索
      if (state.filters.keyword) {
        const keyword = state.filters.keyword.toLowerCase()
        filtered = filtered.filter(ticket => 
          ticket.title?.toLowerCase().includes(keyword) ||
          ticket.description?.toLowerCase().includes(keyword) ||
          ticket.id?.toString().includes(keyword)
        )
      }

      // 日期范围筛选
      if (state.filters.dateRange && state.filters.dateRange.length === 2) {
        const [startDate, endDate] = state.filters.dateRange
        filtered = filtered.filter(ticket => {
          const ticketDate = new Date(ticket.createdAt)
          return ticketDate >= startDate && ticketDate <= endDate
        })
      }

      return filtered
    },

    // 工单统计（包含乐观更新）
    ticketStats: (state) => {
      const allTickets = [...state.optimisticTickets, ...state.tickets]
      const total = allTickets.length
      const open = allTickets.filter(t => t.status === 'OPEN').length
      const inProgress = allTickets.filter(t => t.status === 'IN_PROGRESS').length
      const resolved = allTickets.filter(t => t.status === 'RESOLVED').length
      const closed = allTickets.filter(t => t.status === 'CLOSED').length

      return {
        total,
        open,
        inProgress,
        resolved,
        closed
      }
    },
    
    // 检查是否可以提交
    canSubmit: (state) => {
      const now = Date.now()
      return !state.submitting && (now - state.lastSubmitTime) > state.submitDebounceTime
    }
  },

  actions: {
    /**
     * 获取工单列表
     */
    async fetchTickets(params = {}) {
      this.loading = true
      this.error = null
      
      try {
        const result = await TicketService.list(params)
        console.log('[fetchTickets] 优化版获取到数据:', result)
        
        if (Array.isArray(result)) {
          this.tickets = result
          this.pagination.total = result.length
          console.log(`[fetchTickets] 优化版设置工单列表: ${result.length} 个工单`)
        } else if (result && result.content && Array.isArray(result.content)) {
          // 处理分页响应格式: {content: [...], page: 1, size: 20, totalElements: 30, totalPages: 2}
          this.tickets = result.content
          this.pagination.total = result.totalElements || result.total
          this.pagination.page = result.page || 1
          this.pagination.size = result.size || 20
          console.log(`[fetchTickets] 优化版设置分页工单列表: ${result.content.length} 个工单，总数: ${result.totalElements}`)
        } else if (result && result.records) {
          this.tickets = result.records
          this.pagination.total = result.total
          console.log(`[fetchTickets] 优化版设置工单列表: ${result.records.length} 个工单，总数: ${result.total}`)
        } else {
          this.tickets = []
          this.pagination.total = 0
          console.warn(`[fetchTickets] 优化版未获取到有效数据，收到的数据结构:`, result)
        }
      } catch (error) {
        this.error = error.message || '获取工单列表失败'
        this.tickets = []
        console.error('获取工单失败:', error)
      } finally {
        this.loading = false
      }
    },

    /**
     * 创建工单（带乐观更新）
     */
    async createTicket(ticketData) {
      // 防重复提交检查
      if (!this.canSubmit) {
        const remainingTime = Math.ceil((this.submitDebounceTime - (Date.now() - this.lastSubmitTime)) / 1000)
        ElMessage.warning(`请${remainingTime}秒后再试`)
        return { success: false, message: '提交过于频繁' }
      }
      
      // 设置提交状态
      this.submitting = true
      this.lastSubmitTime = Date.now()
      
      // 生成临时ID用于乐观更新
      const tempId = `temp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      
      // 创建乐观工单对象
      const optimisticTicket = {
        id: tempId,
        ...ticketData,
        status: 'OPEN',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        isOptimistic: true, // 标记为乐观更新
        isPending: true // 标记为pending状态
      }
      
      // 立即添加到乐观列表
      this.optimisticTickets.push(optimisticTicket)
      
      // 记录操作
      this.pendingOperations.set(tempId, {
        type: 'create',
        data: optimisticTicket,
        timestamp: Date.now()
      })
      
      console.log('🔄 乐观更新: 立即添加工单到列表', optimisticTicket)
      
      try {
        // 实际发起API请求
        const result = await TicketService.create(ticketData)
        
        // 请求成功，移除乐观工单，添加真实工单
        this.optimisticTickets = this.optimisticTickets.filter(t => t.id !== tempId)
        this.tickets.unshift(result) // 添加到列表开头
        
        // 清除pending操作
        this.pendingOperations.delete(tempId)
        
        console.log('✅ 工单创建成功，替换乐观工单为真实数据', result)
        
        ElMessage.success('工单创建成功！')
        
        return { success: true, data: result }
      } catch (error) {
        // 请求失败，回滚乐观更新
        console.error('❌ 工单创建失败，回滚乐观更新:', error)
        
        // 移除乐观工单
        this.optimisticTickets = this.optimisticTickets.filter(t => t.id !== tempId)
        this.pendingOperations.delete(tempId)
        
        // 显示错误提示
        const errorMessage = error.message || '创建工单失败'
        ElMessage.error(errorMessage)
        
        return { success: false, message: errorMessage }
      } finally {
        // 重置提交状态（延迟重置，确保防抖）
        setTimeout(() => {
          this.submitting = false
        }, 500)
      }
    },

    /**
     * 更新工单（带乐观更新）
     */
    async updateTicket(ticketId, updates) {
      // 查找工单
      const ticketIndex = this.tickets.findIndex(t => t.id === ticketId)
      if (ticketIndex === -1) {
        ElMessage.error('工单不存在')
        return { success: false }
      }
      
      // 保存原始数据用于回滚
      const originalTicket = { ...this.tickets[ticketIndex] }
      
      // 乐观更新本地数据
      this.tickets[ticketIndex] = {
        ...originalTicket,
        ...updates,
        updatedAt: new Date().toISOString(),
        isOptimistic: true
      }
      
      console.log('🔄 乐观更新: 立即更新工单', this.tickets[ticketIndex])
      
      try {
        // 实际API请求
        const result = await TicketService.update(ticketId, updates)
        
        // 请求成功，更新为真实数据
        this.tickets[ticketIndex] = result
        
        console.log('✅ 工单更新成功', result)
        ElMessage.success('更新成功！')
        
        return { success: true, data: result }
      } catch (error) {
        // 请求失败，回滚到原始数据
        console.error('❌ 工单更新失败，回滚数据:', error)
        this.tickets[ticketIndex] = originalTicket
        
        const errorMessage = error.message || '更新工单失败'
        ElMessage.error(errorMessage)
        
        return { success: false, message: errorMessage }
      }
    },

    /**
     * 删除工单（带乐观更新）
     */
    async deleteTicket(ticketId) {
      // 查找工单
      const ticketIndex = this.tickets.findIndex(t => t.id === ticketId)
      if (ticketIndex === -1) {
        ElMessage.error('工单不存在')
        return { success: false }
      }
      
      // 保存原始数据用于回滚
      const deletedTicket = this.tickets[ticketIndex]
      
      // 乐观删除
      this.tickets.splice(ticketIndex, 1)
      
      console.log('🔄 乐观更新: 立即删除工单', ticketId)
      
      try {
        // 实际API请求
        await TicketService.delete(ticketId)
        
        console.log('✅ 工单删除成功')
        ElMessage.success('删除成功！')
        
        return { success: true }
      } catch (error) {
        // 请求失败，恢复工单
        console.error('❌ 工单删除失败，恢复数据:', error)
        this.tickets.splice(ticketIndex, 0, deletedTicket)
        
        const errorMessage = error.message || '删除工单失败'
        ElMessage.error(errorMessage)
        
        return { success: false, message: errorMessage }
      }
    },

    /**
     * 清除所有乐观更新
     */
    clearOptimisticUpdates() {
      this.optimisticTickets = []
      this.pendingOperations.clear()
    },

    /**
     * 重置提交状态
     */
    resetSubmitState() {
      this.submitting = false
      this.lastSubmitTime = 0
    },

    /**
     * 设置过滤器
     */
    setFilter(key, value) {
      this.filters[key] = value
    },

    /**
     * 清除过滤器
     */
    clearFilters() {
      this.filters = {
        status: '',
        priority: '',
        category: '',
        assignee: '',
        keyword: '',
        dateRange: []
      }
    },

    /**
     * 批量操作
     */
    async batchUpdate(ticketIds, updates) {
      // 实现批量更新的乐观更新逻辑
      // 类似单个更新，但处理多个工单
    }
  }
})

